{% extends "admin/admin_base.html" %}

{% block title %}卡密管理{% endblock %}
{% block breadcrumb %}卡密管理{% endblock %}
{% block content %}
<style>
    /* 统计卡片 */
    .stats-container {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
        gap: 1.5rem;
        margin-bottom: 1.5rem;
    }

    .stat-card {
        background-color: white;
        border-radius: 0.75rem;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        padding: 1.5rem;
        transition: transform 0.2s ease, box-shadow 0.2s ease;
    }

    .stat-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
    }

    .stat-card-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 1rem;
    }

    .stat-card-title {
        color: #86909C;
        font-size: 0.875rem;
        font-weight: 500;
    }

    .stat-card-icon {
        width: 40px;
        height: 40px;
        border-radius: 0.5rem;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.25rem;
    }

    .stat-card-icon.primary {
        background-color: rgba(22, 93, 255, 0.1);
        color: var(--primary-color);
    }

    .stat-card-icon.success {
        background-color: rgba(0, 180, 42, 0.1);
        color: var(--success-color);
    }

    .stat-card-icon.warning {
        background-color: rgba(255, 125, 0, 0.1);
        color: var(--warning-color);
    }

    .stat-card-icon.danger {
        background-color: rgba(245, 63, 63, 0.1);
        color: var(--danger-color);
    }

    .stat-card-value {
        font-size: 1.75rem;
        font-weight: 600;
        margin-bottom: 0.5rem;
    }

    .stat-card-trend {
        display: flex;
        align-items: center;
        gap: 0.25rem;
        font-size: 0.875rem;
    }

    .trend-up {
        color: var(--success-color);
    }

    .trend-down {
        color: var(--danger-color);
    }

    .badge {
        padding: 0.25rem 0.5rem;
        border-radius: 999px;
        font-size: 0.75rem;
        font-weight: 500;
    }

    .badge-success {
        background-color: rgba(0, 180, 42, 0.1);
        color: var(--success-color);
    }

    .badge-danger {
        background-color: rgba(245, 63, 63, 0.1);
        color: var(--danger-color);
    }

    .badge-warning {
        background-color: rgba(255, 125, 0, 0.1);
        color: var(--warning-color);
    }

    .badge-primary {
        background-color: rgba(22, 93, 255, 0.1);
        color: var(--primary-color);
    }

    /* 金牌用户（月度会员） */
    .badge-month {
        background-color: #FFF9C4; /* 浅金背景（接近鎏金质感） */
        color: #D4AF37; /* 金属金色文字 */
        border: 1px solid #FFECB3; /* 浅边框增强层次感 */
    }

    /* 铂金用户（季度会员） */
    .badge-season {
        background-color: #E3F2FD; /* 淡蓝背景（类似铂金冷冽感） */
        color: #1976D2; /* 钴蓝色文字 */
        border: 1px solid #BBDEFB; /* 更浅的蓝边框 */
    }

    /* 至尊用户（年度/管理员） */
    .badge-year,
    .badge-admin {
        background: linear-gradient(135deg, #7B1FA2 0%, #4A148C 100%); /* 紫红渐变（尊贵感） */
        color: #FFFFFF; /* 白色文字高对比 */
        box-shadow: 0 2px 4px rgba(123, 31, 162, 0.15); /* 轻微投影提升立体感 */
    }

    /* 普通用户 */
    .badge-free {
        background-color: #F5F5F5; /* 浅灰背景（中性百搭） */
        color: #616161; /* 深灰文字 */
        border: 1px solid #EEEEEE; /* 极浅灰边框 */
    }

    .action-btn {
        background: none;
        border: none;
        color: #86909C;
        cursor: pointer;
        padding: 0.25rem;
        margin: 0 0.125rem;
        transition: color 0.2s ease;
    }

    /* 提示弹窗（成功/失败反馈） */
    .toast {
        position: fixed;
        top: 20px;
        right: 20px;
        z-index: 9999;
        padding: 16px;
        border-radius: 4px;
        color: #fff;
        font-size: 14px;
        opacity: 0;
        transition: opacity 0.3s ease;
    }

    .toast.success {
        background-color: #52C41A;
    }

    .toast.error {
        background-color: #FF4D4F;
    }

    .toast.show {
        opacity: 1;
    }

/* 用form-row替代form-group，实现label与input同行 */
.kami-form-row {
    display: flex;
    align-items: center; /* 垂直居中对齐 */
    margin-bottom: 16px;
    gap: 16px; /* 标签与输入框之间的间距 */
}

/* 标签固定宽度，确保对齐 */
.kami-form-row .kami-form-label {
    flex: 0 0 80px; /* 固定宽度120px，不伸缩 */
    font-weight: 500;
    color: #1d2129;
    font-size: 14px;
    padding-top: 8px; /* 与输入框基线对齐 */
    text-align: right;
    width: 15%;
    margin-right: 10px;
}

/* 输入框占剩余空间 */
.kami-form-control, .kami-form-select {
    flex: 1; /* 占据剩余空间 */
    padding: 10px 12px;
    border: 1px solid #e5e6eb;
    border-radius: 4px;
    font-size: 14px;
    color: #1d2129;
    transition: border-color 0.2s ease, box-shadow 0.2s ease;
    box-sizing: border-box;
    min-width: 0; /* 解决flex子元素最小宽度问题 */
    width: 80%;
}

.kami-form-control:focus, .kami-form-select:focus {
    outline: none;
    border-color: #165dff;
    box-shadow: 0 0 0 2px rgba(22, 93, 255, 0.1);
}

/* 禁用状态样式 */
.kami-form-control:disabled {
    background-color: #f5f7fa;
    color: #86909c;
    border-color: #e5e6eb;
    cursor: not-allowed;
}
/* 辅助文本样式 */
.kami-form-text {
    margin-top: 4px;
    margin-left: 15%; /* 与标签宽度+间距对齐 */
    font-size: 12px;
    color: #86909c;
}

/* 统计卡片容器 */
.stats-container {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
    gap: 20px;
    padding: 20px;
}

/* 卡片整体 */
.stat-card {
    background: #fff;
    border-radius: 10px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
    padding: 16px;
    transition: transform 0.2s ease, box-shadow 0.2s ease;
}
.stat-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
}

/* 卡片头部 */
.stat-card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
}
.stat-card-title {
    font-size: 16px;
    font-weight: 600;
    color: #495057;
}
.stat-card-icon {
    width: 36px;
    height: 36px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
}
.primary { background-color: #165dff; }
.success { background-color: #28a745; }
.warning { background-color: #ff9800; }
.danger  { background-color: #dc3545; }

/* 卡片数值 */
.stat-card-value {
    font-size: 28px;
    font-weight: 700;
    color: #212529;
    margin-bottom: 12px;
}

/* 统计进度条容器 */
.kami-stat-progress {
    margin-top: 8px;
}

/* 统计文字标签 */
.kami-stat-label {
    display: flex;
    justify-content: space-between;
    font-size: 12px;
    margin-bottom: 4px;
}
.kami-stat-label .used { color: #28a745; }
.kami-stat-label .unused { color: #165dff; }

/* 进度条容器 */
.progress-bar {
    height: 8px;
    background-color: #f1f3f5; /* 底色（未填充部分） */
    border-radius: 4px;
    overflow: hidden;
    position: relative; /* 关键：让子元素可以绝对定位 */
}

/* 进度条基础样式 */
.progress {
    height: 100%;
    position: absolute; /* 叠加显示 */
    top: 0;
    left: 0;
    transition: width 0.6s ease;
}

/* 已使用进度条（靠左） */
.used-progress {
    background-color: #28a745;
    z-index: 2; /* 显示在上面 */
}

/* 未使用进度条（靠右，需要从已使用的右边开始） */
.unused-progress {
    background-color: #165dff;
    left: auto;
    right: 0;
    width: auto;
    z-index:1;
}

/* 百分比显示 */
.kami-stat-percent {
    display: flex;
    justify-content: space-between;
    font-size: 12px;
    font-weight: 600;
    margin-top: 4px;
}
.kami-stat-percent .used { color: #28a745; }
.kami-stat-percent .unused { color: #165dff; }

</style>
<!-- 提示弹窗（用于显示保存成功/失败信息） -->
<div class="toast" id="toast"></div>

<div class="stats-container">
    <!-- 总卡密 -->
    <div class="stat-card">
        <div class="stat-card-header">
            <div class="stat-card-title">总卡密</div>
            <div class="stat-card-icon primary">
                <i class="fas fa-users"></i>
            </div>
        </div>
        <div class="stat-card-value">{{ total_kami }}</div>

        <!-- 百分比进度条 -->
        <div class="kami-stat-progress">
            <div class="kami-stat-label">
                <span class="used">已使用: {{ used_kami }} 张</span>
                <span class="unused">未使用: {{ unused_kami }} 张</span>
            </div>
            <div class="progress-bar">
                <div class="progress used-progress" style="width: {{ used_percent }}%"></div>
                <div class="progress unused-progress" style="width: {{ unused_percent }}%"></div>
            </div>
            <div class="kami-stat-percent">
                <span class="used">{{ used_percent }}%</span>
                <span class="unused">{{ unused_percent }}%</span>
            </div>
        </div>
    </div>

    <!-- 黄金月卡 -->
    <div class="stat-card">
        <div class="stat-card-header">
            <div class="stat-card-title">黄金月卡</div>
            <div class="stat-card-icon success">
                <i class="fas fa-user-check"></i>
            </div>
        </div>
        <div class="stat-card-value">{{ month_count }}</div>

        <div class="kami-stat-progress">
            <div class="kami-stat-label">
                <span class="used">已使用: {{ used_kami_month }} 张</span>
                <span class="unused">未使用: {{ unused_kami_month }} 张</span>
            </div>
            <div class="progress-bar">
                <div class="progress used-progress" style="width: {{ used_percent_month }}%"></div>
                <div class="progress unused-progress" style="width: {{ unused_percent_month }}%"></div>
            </div>
            <div class="kami-stat-percent">
                <span class="used">{{ used_percent_month }}%</span>
                <span class="unused">{{ unused_percent_month }}%</span>
            </div>
        </div>
    </div>

    <!-- 钻石半年卡 -->
    <div class="stat-card">
        <div class="stat-card-header">
            <div class="stat-card-title">钻石半年卡</div>
            <div class="stat-card-icon warning">
                <i class="fas fa-user-plus"></i>
            </div>
        </div>
        <div class="stat-card-value">{{ season_count }}</div>

        <div class="kami-stat-progress">
            <div class="kami-stat-label">
                <span class="used">已使用: {{ used_kami_season }} 张</span>
                <span class="unused">未使用: {{ unused_kami_season }} 张</span>
            </div>
            <div class="progress-bar">
                <div class="progress used-progress" style="width: {{ used_percent_season }}%"></div>
                <div class="progress unused-progress" style="width: {{ unused_percent_season }}%"></div>
            </div>
            <div class="kami-stat-percent">
                <span class="used">{{ used_percent_season }}%</span>
                <span class="unused">{{ unused_percent_season }}%</span>
            </div>
        </div>
    </div>

    <!-- 至尊年卡 -->
    <div class="stat-card">
        <div class="stat-card-header">
            <div class="stat-card-title">至尊年卡</div>
            <div class="stat-card-icon danger">
                <i class="fas fa-user-plus"></i>
            </div>
        </div>
        <div class="stat-card-value">{{ year_count }}</div>

        <div class="kami-stat-progress">
            <div class="kami-stat-label">
                <span class="used">已使用: {{ used_kami_year }} 张</span>
                <span class="unused">未使用: {{ unused_kami_year }} 张</span>
            </div>
            <div class="progress-bar">
                <div class="progress used-progress" style="width: {{ used_percent_year }}%"></div>
                <div class="progress unused-progress" style="width: {{ unused_percent_year }}%"></div>
            </div>
            <div class="kami-stat-percent">
                <span class="used">{{ used_percent_year }}%</span>
                <span class="unused">{{ unused_percent_year }}%</span>
            </div>
        </div>
    </div>
</div>


<!-- 用户表格 -->
<div class="data-table mb-4">
    <div class="table-header">
        <div class="table-title">卡密列表</div>
        <div class="table-actions">
            <form id="searchForm" class="input-group" style="width: 300px;" method="get">
                <input type="text" name="search" class="form-control" placeholder="搜索用户名、ID..."
                       value="{{ search or '' }}">
                <button class="btn btn-primary" type="submit">
                    <i class="fas fa-search"></i>
                </button>
            </form>
            <button class="btn btn-primary" id="addKamiBtn">
                <i class="fas fa-plus"></i> 生成卡密
            </button>
        </div>
    </div>
    <div class="table-responsive">
        <table>
            <thead>
            <tr>
                <th>卡密ID</th>
                <th>卡密Key</th>
                <th>卡密类型</th>
                <th>状态</th>
                <th>创建时间</th>
                <th>激活用户</th>
                <th>激活时间</th>
                <th>备注</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody>
            {% if kamis %}
                {% for kami in kamis %}
                <tr>
                    <td>{{ kami.id }}</td>
                    <td>{{ kami.code }}</td>
                    <td>
                        {% if kami.vip_type.value == 'month' %}
                        <span class="badge badge-month">黄金月卡</span>
                        {% elif kami.vip_type.value == 'season' %}
                        <span class="badge badge-season">铂金季卡</span>
                        {% elif kami.vip_type.value == 'year' %}
                        <span class="badge badge-year">至尊年卡</span>
                        {% else %}
                        <span class="badge badge-free">未知类型</span>
                        {% endif %}
                    </td>
                    <td>
                        {% if kami.is_used == 1 %}
                        <span class="badge badge-success">已使用</span>
                        {% else %}
                        <span class="badge badge-danger">未使用</span>
                        {% endif %}
                    </td>
                    <td>{{ kami.created_at.strftime('%Y-%m-%d %H:%M') if kami.created_at else '--' }}</td>
                    <td>{{ kami.user.username if kami.user and kami.user.username else '--' }}</td>
                    <td>{{ kami.used_at.strftime('%Y-%m-%d %H:%M') if kami.used_at else '--' }}</td>
                    <td>{{ kami.remark if kami.remark else '--' }}</td>
                    <td>
                        <button class="action-btn btn btn-sm btn-warning" title="编辑" data-id="{{ kami.id }}"
                            data-action="editKami">
                            <i class="fas fa-edit"></i>
                        </button>

                        <!-- 禁用/启用按钮 -->
                        {% if kami.is_used == 1 %}
                        <button class="action-btn btn btn-sm btn-danger" title="禁用" data-id="{{ kami.id }}"
                                data-action="disable">
                            <i class="fas fa-ban"></i>
                        </button>
                        {% else %}
                        <button class="action-btn btn btn-sm btn-success" title="启用" data-id="{{ kami.id }}"
                                data-action="disable">
                            <i class="fas fa-check"></i>
                        </button>
                        {% endif %}
                    </td>
                </tr>
                {% endfor %}
            {% else %}
                <tr>
                    <td colspan="9" class="text-center py-4">
                        <i class="fas fa-key text-muted" style="font-size: 1.5rem;"></i>
                        <p class="mt-2 text-muted">暂无卡密数据</p>
                    </td>
                </tr>
            {% endif %}
            </tbody>
        </table>
    </div>
    <div class="pagination-container d-flex justify-content-between align-items-center mt-3">
        <div class="pagination-info">显示 {{ kamis|length }} 条，共 {{ total_kami }} 条</div>
        <div class="pagination">
        <!-- 上一页 -->
        <a href="?page={{ page-1 if page > 1 else 1 }}{% if search %}&search={{ search }}{% endif %}"
           class="btn {% if page == 1 %}btn-outline-secondary disabled{% else %} btn-outline-primary{% endif %}">
            <i class="fas fa-chevron-left"></i>
        </a>

        <!-- 分页按钮（修复 max/min 问题） -->
        {% if total_pages > 0 %}
            {% set start_page = (page - 2) if (page - 2) >= 1 else 1 %}
            {% set end_page = (page + 2) if (page + 2) <= total_pages else total_pages %}
            {% for p in range(start_page, end_page + 1) %}
                <a href="?page={{ p }}{% if search %}&search={{ search }}{% endif %}"
                   class="btn btn-outline-primary {% if p == page %}active{% endif %}">{{ p }}</a>
            {% endfor %}
        {% endif %}

        <!-- 下一页 -->
        <a href="?page={{ page+1 if page < total_pages else total_pages }}{% if search %}&search={{ search }}{% endif %}"
           class="btn {% if page == total_pages %}btn-outline-secondary disabled{% else %} btn-outline-primary{% endif %}">
            <i class="fas fa-chevron-right"></i>
        </a>
    </div>
    </div>
</div>

<!-- 添加 / 编辑模态框 -->
<div class="form-modal" id="addKamiModal">
    <div class="modal-content">
        <form id="addKamiForm">
            <div class="modal-header">
                <h3 class="modal-title">生成卡密</h3>
                <button class="modal-close" id="closeKamiModal" type="button">&times;</button>
            </div>
            <div class="modal-body">
                <div class="kami-form-row" data-edit-only>
                    <label class="kami-form-label">卡密ID</label>
                    <input type="text" name="kami_id" class="kami-form-control" required disabled>
                </div>
                <div class="kami-form-row" data-edit-only>
                    <label class="kami-form-label">卡密Key</label>
                    <input type="text" name="kami_code" class="kami-form-control" disabled>
                </div>
                <div class="kami-form-row" data-edit-only>
                    <label class="kami-form-label">激活天数</label>
                    <input type="number" name="kami_days" class="kami-form-control" disabled>
                </div>
                <div class="kami-form-row" data-edit-only>
                    <label class="kami-form-label">创建时间</label>
                    <input type="date" name="created_at" class="kami-form-control" disabled>
                </div>
                <div class="kami-form-row mb-3">
                    <label class="kami-form-label">卡密类型 <span class="text-danger">*</span></label>
                    <select name="vip_type" class="kami-form-select" required>
                        <option value="month">黄金月卡（30天）</option>
                        <option value="season">铂金季卡（90天）</option>
                        <option value="year">至尊年卡（365天）</option>
                    </select>
                </div>
                <div class="kami-form-row" data-edit-only>
                    <label class="kami-form-label">状态<span class="text-danger">*</span></label>
                    <select name="kami_is_used" class="kami-form-control" required>
                        <option value="1">1 - 已使用</option>
                        <option value="0">0 - 未使用</option>
                    </select>
                </div>
                <div class="kami-form-row" data-edit-only>
                    <label class="kami-form-label">过期时间<span class="text-danger">*</span></label>
                    <input type="date" name="used_at" class="kami-form-control" required >
                </div>

                <div class="kami-form-row mb-3" data-add-only>
                    <label class="kami-form-label">生成数量<span class="text-danger">*</span></label>
                    <input type="number" name="count" class="kami-form-control" value="1" min="1" max="100" required>
                    <div class="kami-form-text">单次最多生成100张卡密</div>
                </div>
                <div class="kami-form-row mb-3">
                    <label class="kami-form-label">备注</label>
                    <input type="text" name="remark" class="kami-form-control" placeholder="2024年10月活动卡密">
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-outline" id="cancelAddKami" type="button">取消</button>
                <button class="btn btn-primary" type="submit">生成卡密</button>
            </div>
        </form>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
    document.addEventListener("DOMContentLoaded", () => {
        const addKamiBtn = document.getElementById("addKamiBtn");
        const addKamiModal = document.getElementById("addKamiModal");
        const closeKamiModal = document.getElementById("closeKamiModal");
        const cancelAddKami = document.getElementById("cancelAddKami");
        const submitKamiBtn = addKamiModal.querySelector("button[type='submit']");
        const kamiForm = document.getElementById("addKamiForm");

        // 调试：打印元素是否获取成功
        console.log("卡密表单元素：", kamiForm); // 应显示HTMLFormElement
        console.log("提交按钮：", submitKamiBtn); // 应显示HTMLButtonElement

        // 打开生成卡密模态框
        addKamiBtn.addEventListener("click", () => {
            setFormMode('add');
            resetForm();
            submitKamiBtn.textContent = "添加卡密";
            submitKamiBtn.dataset.action = "add";
            addKamiModal.classList.add("show");
        });

        closeKamiModal.addEventListener("click", () => {
            addKamiModal.classList.remove("show");
            setTimeout(() => window.location.reload(), 100);
        });
        cancelAddKami.addEventListener("click", () => {
            addKamiModal.classList.remove("show");
            setTimeout(() => window.location.reload(), 100);
        });

        // 点击模态框外部关闭
        window.addEventListener("click", (e) => {
            if (e.target.classList.contains("form-modal")) {
                e.target.classList.remove("show");
                setTimeout(() => window.location.reload(), 100);
            }
        });

        // 表格操作按钮
        document.querySelectorAll(".action-btn").forEach(btn => {
            btn.addEventListener("click", async () => {
                const kamiId = btn.dataset.id;
                const action = btn.dataset.action;
                const titleEl = addKamiModal.querySelector(".modal-title");
                if (action === "editKami") {
                    const res = await fetch(`/admin/kami/action?action=${action}`, {
                        method: "POST",
                        headers: {"Content-Type": "application/json"},
                        body: JSON.stringify({ kami_id: kamiId, action: 'get'})
                    });
                    const data = await res.json();
                    console.log(data);

                    if (!data.success) return alert(data.msg);
                    setFormMode('edit');
                    fillForm(data.kami);
                    titleEl.textContent = "编辑卡密";
                    submitKamiBtn.textContent = "保存修改";
                    submitKamiBtn.dataset.action = action;
                    submitKamiBtn.dataset.kamiId = kamiId;

                    addKamiModal.classList.add("show");
                }

                if (action === "disable") {
                    if (!confirm(`确定要修改ID：${kamiId}这张卡密吗？`)) return;
                    const res = await fetch(`/admin/kami/action?action=${action}`, {
                        method: "POST",
                        headers: {"Content-Type": "application/json"},
                        body: JSON.stringify({ kami_id: kamiId })
                    });
                    const data = await res.json();
                    // alert(data.msg);
                    if (data.success) {
                        location.reload();
                        showToast('成功', data.msg, 'success');
                    } else {
                        showToast('错误', data.msg || '生成失败', 'error');
                    }

                }
            });
        });

        // 保存/提交按钮点击
        submitKamiBtn.addEventListener("click", async (e) => {
            e.preventDefault();
            const action = submitKamiBtn.dataset.action;
            const kamiId = submitKamiBtn.dataset.kamiId;
            const formData = new FormData(kamiForm);
            console.log("FormData中的数据：");
            formData.forEach((value, key) => {
                console.log(`${key}: ${value}`);
            });
            if (action === "editKami") {
                const payload = {
                    kami_id: kamiId,
                    vip_type: kamiForm.vip_type.value,
                    is_used: kamiForm.kami_is_used.value,
                    used_at: kamiForm.used_at.value
                };

                const res = await fetch(`/admin/kami/action?action=${action}`, {
                    method: "POST",
                    headers: {"Content-Type": "application/json"},
                    body: JSON.stringify(payload)
                });

                const data = await res.json();
                if (data.success) {
                    addKamiModal.classList.remove("show");
                    showToast('成功', data.msg, 'success');
                    // location.reload();  // 刷新表格
                    setTimeout(() => window.location.reload(), 1500);
                } else {
                    showToast('错误', data.msg || '生成失败', 'error');
                }
            }  else {
                fetch('/admin/kami/generate', {
                    method: 'POST',
                    body: formData,
                    credentials: 'include' // 携带登录状态
                })
                .then(res => res.json())
                .then(data => {
                    if (data.success) {
                        showToast('成功', data.msg, 'success');
                        // 刷新页面，显示新卡密
                        setTimeout(() => window.location.reload(), 1500);
                    } else {
                        showToast('错误', data.msg || '生成失败', 'error');
                    }
                })
                .catch(err => {
                    console.error('生成卡密失败:', err);
                    showToast('错误', '网络异常，请重试', 'error');
                });
            }
        });

        function resetForm() {
            kamiForm.reset();
            kamiForm.querySelectorAll("input, select").forEach(el => el.disabled = false);
            submitKamiBtn.dataset.kamiId = "";
        }

        function fillForm(kami) {
            kamiForm.kami_id.value = kami.id || "";
            kamiForm.kami_code.value = kami.code || "";
            kamiForm.vip_type.value = kami.vip_type || "";
            kamiForm.kami_days.value = kami.days || "";
            kamiForm.kami_is_used.value = kami.is_used || 0;
            kamiForm.created_at.value = formatDateForInput(kami.created_at);
            // kamiForm.used_at.value = kami.used_at || "";
            kamiForm.used_at.value = kami.used_at
                ? new Date(kami.used_at).toISOString().split("T")[0]
                : new Date().toISOString().split("T")[0];
            kamiForm.remark.value = kami.remark || "";
        }
    });

    // --- 3. 切换表单模式的核心函数 ---
    function setFormMode(mode) {
        // mode: 'add' 或 'edit'
        // 根据模式显示/隐藏字段组
        document.querySelectorAll('[data-add-only]').forEach(el => {
            el.style.display = mode === 'add' ? 'block' : 'none';
        });
        document.querySelectorAll('[data-edit-only]').forEach(el => {
            el.style.display = mode === 'edit' ? 'block' : 'none';
        });
        document.querySelectorAll('[data-view-only]').forEach(el => {
            el.style.display = mode === 'edit' ? 'block' : 'none';
        });
    }

    // 日期格式化工具函数（可复用）
    function formatDateForInput(dateStr) {
        if (!dateStr || typeof dateStr !== "string") return "";
        try {
            const date = new Date(dateStr);
            // 验证是否为有效日期（避免 Invalid Date）
            if (isNaN(date.getTime())) return "";
            return date.toISOString().split("T")[0];
        } catch (err) {
            console.error("格式化日期失败：", err);
            return "";
        }
    }

    // 4. 提示弹窗函数
    function showToast(title, msg, type) {
        const toast = document.getElementById('toast');
        toast.className = `toast ${type} show`;
        toast.innerHTML = `<strong>${title}!</strong> ${msg}`;
        // 3秒后自动隐藏
        setTimeout(() => {
            toast.className = 'toast';
        }, 3000);
    }

</script>
{% endblock %}
